import { createStore } from 'vuex'
import useStorage from "@/utils/useStorage";
import {http} from "@/api";
import {ElMessage} from "element-plus";
import router from "@/router";
const storage = useStorage()
const TokenKey = 'askjina_to2_token'
const UserInfoKey = 'askjina_to2_userInfo'
export default createStore({
  state: {
      userInfo: storage.getItem(UserInfoKey) || {},
      token: storage.getItem(TokenKey) || ''
  },
  getters: {
      userInfo: state => state.userInfo,
      token: state => state.token
  },
  mutations: {
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo;
            storage.setItem(UserInfoKey, userInfo);
        },
        setToken(state, token) {
            state.token = token;
            storage.setItem(TokenKey, token);
        },
        logout(state) {
            state.userInfo = {};
            state.token = '';
            storage.removeItem(UserInfoKey);
            storage.removeItem(TokenKey);
            router.replace('/user/login')
        }
  },
  actions: {
      login({ commit }, userInfo) {
          return new Promise((resolve, reject) => {
              http.login(userInfo).then(res => {
                      if (res.code === 200) {
                          commit('setUserInfo', res.data);
                          commit('setToken', res.data.token);
                          resolve(res);
                      } else {
                            ElMessage.error(res.msg)
                            reject(res)
                      }
              }).catch(err => {
                    reject(err)
              })
          })
      },
      register({ commit }, userInfo) {
          return new Promise((resolve, reject) => {
              http.register(userInfo).then(res => {
                  if (res.code === 200) {
                      commit('setUserInfo', res.data);
                      commit('setToken', res.data.token);
                      resolve(res);
                  } else {
                        ElMessage.error(res.msg)
                        reject(res)
                  }
              }).catch(err => {
                  reject(err)
              })
          })
      }
  },
  modules: {
  }
})
